package com.ksm.client.document.view;

import java.util.ArrayList;
import java.util.List;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ChangeEvent;
import com.google.gwt.event.dom.client.ChangeHandler;
import com.google.gwt.i18n.client.NumberFormat;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiFactory;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.ui.IsWidget;
import com.google.gwt.user.client.ui.ResizeComposite;
import com.google.gwt.user.client.ui.Widget;
import com.google.inject.Singleton;
import com.ksm.client.document.DocumentProperties;
import com.ksm.client.document.JustificatifProperties;
import com.ksm.client.document.presenter.DocumentJustificatifPresenter.IDocumentJustificatifView;
import com.ksm.client.document.presenter.IDocumentJustificatifPresenter;
import com.ksm.transfer.dto.JustificatifDTO;
import com.sencha.gxt.core.client.IdentityValueProvider;
import com.sencha.gxt.data.shared.ListStore;
import com.sencha.gxt.widget.core.client.event.CellClickEvent;
import com.sencha.gxt.widget.core.client.event.SelectEvent;
import com.sencha.gxt.widget.core.client.event.SubmitCompleteEvent;
import com.sencha.gxt.widget.core.client.form.FileUploadField;
import com.sencha.gxt.widget.core.client.form.FormPanel;
import com.sencha.gxt.widget.core.client.form.NumberPropertyEditor;
import com.sencha.gxt.widget.core.client.form.NumberPropertyEditor.DoublePropertyEditor;
import com.sencha.gxt.widget.core.client.grid.CheckBoxSelectionModel;
import com.sencha.gxt.widget.core.client.grid.ColumnConfig;
import com.sencha.gxt.widget.core.client.grid.ColumnModel;
import com.sencha.gxt.widget.core.client.grid.Grid;
import com.sencha.gxt.widget.core.client.grid.GridView;
import com.sencha.gxt.widget.core.client.info.Info;

@Singleton
public class DocumentJustificatifView extends ResizeComposite implements IsWidget, IDocumentJustificatifView {

	private Long selectionnedDocumentId = null;

	private IDocumentJustificatifPresenter presenter;

	interface MyUiBinder extends UiBinder<Widget, DocumentJustificatifView> {
	}

	private static MyUiBinder uiBinder = GWT.create(MyUiBinder.class);

	IdentityValueProvider<JustificatifDTO> identity = new IdentityValueProvider<JustificatifDTO>();
	final CheckBoxSelectionModel<JustificatifDTO> sm = new CheckBoxSelectionModel<JustificatifDTO>(identity);

	@UiField(provided = true)
	final NumberFormat numberFormat = NumberFormat.getFormat("0.00");
	@UiField(provided = true)
	NumberPropertyEditor<Double> doublePropertyEditor = new DoublePropertyEditor();

	@UiField(provided = true)
	final FormPanel form = new FormPanel();

	@UiField
	FileUploadField filename;

	@UiField
	Grid<JustificatifDTO> justificatifGrid;
	@UiField
	GridView<JustificatifDTO> justificatifGridView;
	@UiField
	ColumnModel<JustificatifDTO> justificatifColumnModel;
	@UiField
	ListStore<JustificatifDTO> justificatifStore;

	@UiFactory
	ColumnModel<JustificatifDTO> createJustificatifColumnModel() {
		return justificatifColumnModel;
	}

	@UiFactory
	ListStore<JustificatifDTO> createListStore() {
		return justificatifStore;
	}

	private static final String UPLOAD_ACTION_URL = GWT.getModuleBaseURL() + "upload";

	private String uploadedFileName;
	private boolean newFile;

	private Widget currentWidget = null;

	DocumentProperties props = GWT.create(DocumentProperties.class);
	private JustificatifProperties justificatifProperties = GWT.create(JustificatifProperties.class);

	public Widget asWidget() {
		if (null == currentWidget) {
			initializeColumnModel();
			justificatifStore = getJustificatifStore();
			currentWidget = uiBinder.createAndBindUi(this);

			filename.addChangeHandler(new ChangeHandler() {

				@Override
				public void onChange(ChangeEvent event) {
					Info.display("File Changed", "You selected " + filename.getValue());
				}
			});

			form.setAction(UPLOAD_ACTION_URL);
			form.setEncoding(FormPanel.Encoding.MULTIPART);
			form.setMethod(FormPanel.Method.POST);
			form.addSubmitCompleteHandler(new SubmitCompleteEvent.SubmitCompleteHandler() {

				public void onSubmitComplete(SubmitCompleteEvent event) {
					parseUploadFileResult(event);

				}

			});
			initForm();

		}
		return currentWidget;
	}

	private final void parseUploadFileResult(SubmitCompleteEvent event) {
		Info.display("File Changed", "You submited " + filename.getValue());
		String resultHtml = event.getResults();
		Info.display("Upload Response", resultHtml);

		if (resultHtml != null && !resultHtml.contains("ERROR")) {
			uploadedFileName = resultHtml.trim();
			newFile = true;
			presenter.saveDocument();
		}
	}

	private ListStore<JustificatifDTO> getJustificatifStore() {
		ListStore<JustificatifDTO> justificatifStore = new ListStore<JustificatifDTO>(justificatifProperties.key());
		justificatifStore.add(new JustificatifDTO(1L, 1L, "test1.pdf", "", ""));
		justificatifStore.add(new JustificatifDTO(1L, 2L, "test2.pdf", "", ""));
		return justificatifStore;
	}

	private void initializeColumnModel() {

		// ID
		ColumnConfig<JustificatifDTO, Long> idColonne = new ColumnConfig<JustificatifDTO, Long>(justificatifProperties.id(), 100, "Id");
		// NAME
		ColumnConfig<JustificatifDTO, String> nameColonne = new ColumnConfig<JustificatifDTO, String>(justificatifProperties.name(), 200, "Name");

		List<ColumnConfig<JustificatifDTO, ?>> columnsList = new ArrayList<ColumnConfig<JustificatifDTO, ?>>();
		columnsList.add(sm.getColumn());
		columnsList.add(idColonne);
		columnsList.add(nameColonne);
		justificatifColumnModel = new ColumnModel<JustificatifDTO>(columnsList);
	}

	private void initForm() {

		justificatifGrid.setSelectionModel(sm);
		justificatifGrid.setBorders(false);
		justificatifGrid.getView().setStripeRows(true);
		justificatifGrid.getView().setColumnLines(true);
		uploadedFileName = null;
		newFile = false;
	}

	@UiHandler("justificatifGrid")
	void onCellClick(CellClickEvent event) {

		JustificatifDTO justificatifClicked = justificatifStore.get(event.getRowIndex());
		// type.setValue(documentClicked.getType());
		// date.setValue(documentClicked.getDate());
		// interlocuteur.setValue(documentClicked.getInterlocuteur());
		// montant.setValue(documentClicked.getMontant());
		// documentPopup.show();
		//
		// Window.open(GWT.getModuleBaseURL() + "download?filename=" +
		// String.valueOf(documentClicked.getFilename()), "", "");

		presenter.showPreviewJustifcatif(justificatifClicked);

	}

	@UiHandler("uploadButton")
	public void onUpload(SelectEvent evt) {
		String fileNames = filename.getValue();
		if (fileNames.length() == 0) {
			// The button isn't active unless we have a file to import
			return;
		}
		form.submit();
	}

	@UiHandler("resetButton")
	public void onReset(SelectEvent evt) {
		filename.reset();
		form.reset();
	}

	public void setListStore(ListStore<JustificatifDTO> listeStore, Long documentId) {
		this.selectionnedDocumentId = documentId;
		this.justificatifStore = listeStore;
		justificatifGrid.reconfigure(this.justificatifStore, justificatifColumnModel);
	}

	public void addToStore(JustificatifDTO jDto) {
		this.selectionnedDocumentId = jDto.getId();
		this.justificatifStore.add(0, jDto);
		justificatifGrid.reconfigure(this.justificatifStore, justificatifColumnModel);
	}

	public IDocumentJustificatifPresenter getPresenter() {
		return presenter;
	}

	public void setPresenter(IDocumentJustificatifPresenter presenter) {
		this.presenter = presenter;
	}

	public Long getSelectionnedDocumentId() {
		return selectionnedDocumentId;
	}

	public void setSelectionnedDocumentId(Long selectionnedDocumentId) {
		this.selectionnedDocumentId = selectionnedDocumentId;
	}

	public String getUploadedFileName() {
		return uploadedFileName;
	}

	public void setUploadedFileName(String uploadedFileName) {
		this.uploadedFileName = uploadedFileName;
	}

}